package cn.autumnorange.authorization.security.security;

import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContext;


public class AccessTokenThread implements Runnable {
    public static String appid = "";
    public static String appsecret = "";
    public static AccessToken accessToken = null;
    private WebApplicationContext webApplicationContext;

    public AccessTokenThread(WebApplicationContext webApplicationContext) {
        this.webApplicationContext = webApplicationContext;
    }


    //
//    @Autowired
//    private WebApplicationContext webApplicationContext;
    @Override
    public void run() {
        while (true) {
            try {
                accessToken = CommonUtil.getAccessToken(appid, appsecret);
                if (null != accessToken) {
                    ServletContext servletContext = webApplicationContext.getServletContext();
                    servletContext.setAttribute("access_token", accessToken.getAccessToken());
                    Thread.sleep((accessToken.getExpiresIn() - 200) * 1000);
                } else {
                    Thread.sleep(60 * 1000);
                }
            } catch (Exception e) {
                try {
                    Thread.sleep(60 * 1000);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                e.printStackTrace();
            }
        }
    }
}

